<template>
  <div>
    <div v-if="viewMode" class="text-right mb-2">
      <el-button size="small" icon="el-icon-printer" @click="handlePrint">打印</el-button>
    </div>
    <div :id="printId" v-loading="loading">
      <h5 class="text-center">项目审批表 （权限内）</h5>
      <table class="table table-sm table-bordered vertical-align-middle text-center">
        <tbody>
          <tr>
            <td>借款人名称</td>
            <td colspan="2">{{ related.customer_name || '' }}</td>
            <td>法定代表人</td>
            <td colspan="2">{{ related.corp_name }}</td>
          </tr>
          <tr>
            <td>申请金额</td>
            <td colspan="2">{{ related.apply_funds || '' }}万元</td>
            <td>申请期限</td>
            <td colspan="2">{{ related.load_years || '' }}年</td>
          </tr>
          <tr>
            <td>贷款银行</td>
            <td colspan="2">{{ related.bank_name }}</td>
            <td>贷款利率（年）</td>
            <td colspan="2" class="report-input-td">{{ related.load_rate || '-' }}%</td>
          </tr>
          <tr>
            <td>审批金额</td>
            <td colspan="2" class="report-input-td">{{ data.res_funds }}</td>
            <td>期限</td>
            <td colspan="2" class="report-input-td">{{ related.approval_load_years || '-' }}年</td>
          </tr>
          <tr>
            <td>担保费率</td>
            <td colspan="2" class="report-input-td">{{ related.gua_rate || '-' }}%</td>
            <td>评审费</td>
            <td colspan="2" class="report-input-td">{{ related.approval_fee || '-' }}元</td>
          </tr>
          <tr>
            <td>资金用途</td>
            <td colspan="5" class="text-left pl-3">{{ related.funds_use_dir }}</td>
          </tr>
          <tr>
            <td>项目基本介绍</td>
            <td colspan="5" class="report-input-td text-left">
              <div class="text-indent p-2">{{ related.project_des || '-' }}</div>
            </td>
          </tr>
          <tr>
            <td>反担保措施</td>
            <td colspan="5" class="report-input-td text-left">
              <div class="text-indent p-2">{{ related.counter_guarantee || '-' }}</div>
            </td>
          </tr>
          <tr>
            <td>项目主审</td>
            <td colspan="2">{{ related.res_a_name }}</td>
            <td>项目辅审</td>
            <td colspan="2">{{ related.res_b_name }}</td>
          </tr>
          <tr>
            <td width="13%">风控员意见</td>
            <td width="20%" class="report-input-td text-left">
              <div v-if="baseInfoView || !isRiskStaff" class="p-2">
                {{ related.city_res_option_risk_point || '' }}
                <div v-if="+related.city_res_status_risk_point !== 0">
                  <div>签字：{{ related.city_res_person_risk_point }}</div>
                  <div>日期：{{ related.city_res_date_risk_point | toDate }}</div>
                </div>
              </div>
              <div v-else>
                <textarea
                  rows="4"
                  class="form-control"
                  v-model="data.city_res_option_risk_point"
                ></textarea>
                <div class="sign-bottom px-2">
                  <div>签字：{{ userName }}</div>
                  <div>日期：{{ new Date() | toDate }}</div>
                </div>
              </div>
            </td>
            <td width="13%">业务员意见</td>
            <td width="18%" class="report-input-td text-left text-area-height">
              <div v-if="baseInfoView || !isAbApproval" class="p-2">
                {{ related.city_res_option || '' }}
                <div v-if="+related.city_res_status !== 0">
                  <div>签字：{{ related.city_res_a_name }}</div>
                  <div>日期：{{ related.city_res_date | toDate }}</div>
                </div>
              </div>
              <div v-else>
                <textarea rows="4" class="form-control" v-model="data.city_res_option"></textarea>
                <div class="sign-bottom px-2">
                  <div>签字：{{ userName }}</div>
                  <div>日期：{{ new Date() | toDate }}</div>
                </div>
              </div>
            </td>
            <td :rowspan="2" width="10%">
              <div>农业担保部意见</div>
            </td>
            <td :rowspan="2" class="text-left p-2 qx-option-td" width="20%">
              <div class="d-flex flex-column justify-content-around qx-option">
                <div class="flex-1 py-2">
                  <div>业务员： {{ related.res_option || '' }}</div>
                  <div v-if="+related.res_status !== 0">
                    <div>签字：{{ related.res_person }}</div>
                    <div>日期：{{ related.res_date | toDate }}</div>
                  </div>
                </div>
                <div class="flex-1 py-2">
                  <div>业务主管： {{ related.res_option_bus || '' }}</div>
                  <div v-if="+related.res_status_bus !== 0">
                    <div>签字：{{ related.res_person_bus }}</div>
                    <div>日期：{{ related.res_date_bus | toDate }}</div>
                  </div>
                </div>
                <div class="flex-1 py-2">
                  <div>风控员： {{ related.res_option_risk_point || '' }}</div>
                  <div v-if="+related.res_status_risk_point !== 0">
                    <div>签字：{{ related.res_person_risk_point }}</div>
                    <div>日期：{{ related.res_date_risk_point | toDate }}</div>
                  </div>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>风控主管意见</td>
            <td class="report-input-td text-left">
              <div v-if="baseInfoView || !isRiskManage" class="p-2">
                {{ related.city_res_option_risk || '' }}
                <div v-if="+related.city_res_status_risk !== 0">
                  <div>签字：{{ related.city_res_person_risk }}</div>
                  <div>日期：{{ related.city_res_date_risk | toDate }}</div>
                </div>
              </div>
              <div v-else>
                <textarea
                  rows="4"
                  class="form-control"
                  v-model="data.city_res_option_risk"
                ></textarea>
                <div class="sign-bottom px-2">
                  <div>签字：{{ userName }}</div>
                  <div>日期：{{ new Date() | toDate }}</div>
                </div>
              </div>
            </td>
            <td>业务主管意见</td>
            <td class="report-input-td text-left text-area-height">
              <div v-if="baseInfoView || !isBusApproval" class="p-2">
                {{ related.city_res_option_bus || '' }}
                <div v-if="+related.city_res_status_bus !== 0">
                  <div>签字：{{ related.city_res_person_bus }}</div>
                  <div>日期：{{ related.city_res_date_bus | toDate }}</div>
                </div>
              </div>
              <div v-else>
                <textarea
                  rows="4"
                  class="form-control"
                  v-model="data.city_res_option_bus"
                ></textarea>
                <div class="sign-bottom px-2">
                  <div>签字：{{ userName }}</div>
                  <div>日期：{{ new Date() | toDate }}</div>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div>风控部主管意见</div>
              <div>(农业担保部)</div>
            </td>
            <td colspan="5" class="text-left">
              <div>{{ related.res_option_risk || '' }}</div>
              <div
                v-if="+related.res_status_risk !== 0"
                class="d-flex justify-content-between pt-2"
              >
                <div>签字：{{ related.res_person_risk }}</div>
                <div class="w-50">日期：{{ related.res_date_risk | toDate }}</div>
              </div>
            </td>
          </tr>
          <tr>
            <td>
              <div>有权审批人意见</div>
              <div>(农业担保部)</div>
            </td>
            <td colspan="5" class="text-left">
              <div>{{ related.res_option_corp || '' }}</div>
              <div
                v-if="+related.res_status_corp !== 0"
                class="d-flex justify-content-between pt-2"
              >
                <div>签字：{{ related.res_person_corp }}</div>
                <div class="w-50">日期：{{ related.res_date_corp | toDate }}</div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="text-center" v-if="buttonEdit">
        <el-button class="btn-long" type="primary" @click="handlePass">通过</el-button>
        <el-button class="btn-long" type="danger" @click="handleReject">不通过</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { printA4 } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { dateFormat } from '@/common/utils/common'

export default {
  props: {
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'customer_related',
      related: {},
      newDate: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
      data: {
        res_funds: '',
        counter_guarantee: '',

        city_res_a_name: '',
        city_res_option: '',
        city_res_date: '',
        city_res_status: 0,

        city_res_person_risk_point: '',
        city_res_status_risk_point: 0,
        city_res_option_risk_point: '',
        city_res_date_risk_point: '',

        city_res_person_risk: '',
        city_res_status_risk: 0,
        city_res_option_risk: '',
        city_res_date_risk: '',

        city_res_date_bus: '',
        city_res_option_bus: '',
        city_res_person_bus: '',
        city_res_status_bus: 0,
      },
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'job']),
    // 是否是ab角审批
    userName() {
      return this.user.realName
    },
    isRefuse() {
      const keys = [
        'res_status',
        'res_status_bus',
        'res_status_risk_point',
        'city_res_status',
        'city_res_status_risk_point',
        'city_res_status_risk',
        'city_res_status_bus',
      ]
      for (let key of keys) {
        if (+this.related[key] === 2) {
          return true
        }
      }
      return false
    },
    isChangeOption() {
      return +this.related.res_status_risk === 0
    },
    isAbApproval() {
      return this.userId === this.related.city_res_a && this.isChangeOption
    },
    isRiskStaff() {
      return this.userId === this.related.city_res_user_id_risk_point && this.isChangeOption
    },
    isRiskManage() {
      return (
        +this.related.city_res_status_risk_point === 1 &&
        this.job === 'org_r_manage' &&
        this.isChangeOption
      )
    },
    isBusApproval() {
      return (
        +this.related.city_res_status === 1 && this.job === 'org_c_manage' && this.isChangeOption
      )
    },
    baseInfoView() {
      return this.viewMode || this.isRefuse
    },
    buttonEdit() {
      return (
        !this.baseInfoView &&
        (this.isAbApproval || this.isRiskStaff || this.isRiskManage || this.isBusApproval)
      )
    },
    printId() {
      return `investigate-approve-${this.queryId}`
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getRelatedData() // 任务里面没有返回审批的大量字段需自己重新请求
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    validator() {
      if (!this.data.counter_guarantee) {
        this.$message.error('请输入反担保措施！')
        return false
      }
      return true
    },
    validatorOption() {
      if (this.isAbApproval && !this.data.city_res_option) {
        this.$message.warning('请输入业务员意见')
        return false
      }
      if (this.isRiskStaff && !this.data.city_res_option_risk_point) {
        this.$message.warning('请输入风控员意见')
        return false
      }
      if (this.isRiskManage && !this.data.city_res_option_risk) {
        this.$message.warning('请输入风控主管意见')
        return false
      }
      if (this.isBusApproval && !this.data.city_res_option_bus) {
        this.$message.warning('请输入业务主管意见')
        return false
      }
      return true
    },
    setOptionStatus(status) {
      if (this.isAbApproval) {
        this.data.city_res_a_name = this.userName
        this.data.city_res_date = this.newDate
        this.data.city_res_status = status
      }
      if (this.isRiskStaff) {
        this.data.city_res_person_risk_point = this.userName
        this.data.city_res_date_risk_point = this.newDate
        this.data.city_res_status_risk_point = status
      }
      if (this.isRiskManage) {
        this.data.city_res_person_risk = this.userName
        this.data.city_res_date_risk = this.newDate
        this.data.city_res_status_risk = status
      }
      if (this.isBusApproval) {
        this.data.city_res_person_bus = this.userName
        this.data.city_res_date_bus = this.newDate
        this.data.city_res_status_bus = status
      }
    },
    handleReject() {
      if (!this.validatorOption()) return
      this.setOptionStatus(2)
      const data = {}
      Object.keys(this.data).forEach(key => {
        if (this.data[key]) {
          data[key] = this.data[key]
        }
      })
      this.$utils
        .msgbox({
          message: `确定拒绝项目：${this.related.customer_name}?`,
          type: 'error',
          beforeClose: () => this.updateData(data),
        })
        .then(() => {
          this.$message.success('操作成功！')
          this.$emit('success', true)
        })
        .catch(() => this.$message.error('操作失败，请重试！'))
    },
    updateData(data) {
      return this.$api.updateData(this.$serviceName, this.tableName, this.queryId, data)
    },
    handlePass() {
      if (!this.validator() || !this.validatorOption()) return
      this.setOptionStatus(1)
      const data = {}
      Object.keys(this.data).forEach(key => {
        if (this.data[key]) {
          data[key] = this.data[key]
        }
      })
      this.updateData(data)
        .then(() => {
          this.$message.success('操作成功！')
          this.$emit('success', true)
        })
        .catch(() => this.$message.error('操作失败，请重试！'))
    },
    initData(data) {
      Object.keys(this.data).forEach(key => {
        this.data[key] = data[key] || ''
      })
      this.data.res_funds = +data.res_funds || data.approved_funds
    },
    getRelatedData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, {
          'customer_related_id.eq': this.queryId,
        })
        .then(res => {
          this.related = (res && res.data && res.data.length && res.data[0]) || {}
          this.initData(this.related)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handlePrint() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
        .qx-option {
          min-height: 280px;
        }
        .text-area-height {
          height: 120px;
        }
        .text-indent {
          text-indent: 2rem;
        }
      `
      )
    },
  },
}
</script>
<style lang="scss" scoped>
.text-area-height {
  height: 120px;
}
.vertical-align-middle td {
  vertical-align: middle;
}
.text-indent {
  text-indent: 2rem;
}
.sign-bottom {
  background-color: #ffe;
}
.qx-option {
  min-height: 200px;
  padding: 4px;
  // position: absolute;
  // top: 0;
  // left: 0;
  // bottom: 0;
  // right: 0;
  // height: 100%;
}
.qx-option-td {
  position: relative;
}
</style>
